package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * *  ?")
    public void processTimeoutOrder() {
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);//当前时间减去15分钟
        List<Orders> orders = orderMapper.getOrdersByST(Orders.PENDING_PAYMENT, time);
        if (orders != null) {
            orders.forEach(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason(MessageConstant.ORDER_TIME_OUT);
                orderMapper.update(order);
                log.info("取消订单"+order.getNumber());
            });
        }
    }

    /**
     * 处理“派送中”订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);//凌晨点
        List<Orders> orders =  orderMapper.getOrdersByST(Orders.DELIVERY_IN_PROGRESS,time);
        if (orders!=null){
            orders.forEach(order->{
                order.setStatus(Orders.COMPLETED);//修改状态为已确认
                orderMapper.update(order);
            });
        }
    }
}
